//
//  ZCameraPicker.m
//  danpin
//
//  Created by chuangjia on 5/8/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "ZCameraPicker.h"
#import "viewconfig.h"
#import "KxMenu.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ZCameraPickerCell.h"
#import "ZCameraViewController.h"
#import "ZCameraPhotoCrop.h"
@interface ZCameraPicker ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    
}
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *assets;
@property (nonatomic, strong) ALAssetsGroup *assetsGroup;
@property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
@property (nonatomic, strong) NSMutableArray *groups;
//
@property (nonatomic, strong) UIImage *cameraImage;
@property(nonatomic,strong)UILabel *TitleLabel;
@property(nonatomic,strong)UIButton *leftBtn;
@property(nonatomic,strong)UIButton *rightBtn;
@end

@implementation ZCameraPicker

//@synthesize type=_type;
//@synthesize rank_id=_rank_id;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    // Do any additional setup after loading the view.
    [self initData];
    [self initNavView];
    [self initCollectionView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
      NSLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)dealloc
{
    self.collectionView =nil;
    self.assets=nil;
    self.assetsGroup=nil;
    self.assetsLibrary=nil;
    self.groups=nil;
    //
    self.cameraImage=nil;
    self.TitleLabel=nil;
    self.leftBtn=nil;
    self.rightBtn=nil;
//    NSLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)initNavView
{
    UIView* topView = [[UIView alloc]init];
    topView.backgroundColor = [UIColor whiteColor];
    topView.frame = CGRectMake(0, 0, DEVICE_WIDTH, NAVBAR_HIGHT-1);
    
    //
    _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftBtn.backgroundColor =[UIColor clearColor];
    _leftBtn.tag =1;
    _leftBtn.titleLabel.font = FONT(14);
    [_leftBtn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    _leftBtn.frame =CGRectMake(0,(NAVBAR_HIGHT-44)/2+10, 44, 44);
    [_leftBtn addTarget:self action:@selector(clieckEvent:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:_leftBtn];
    
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.backgroundColor =[UIColor clearColor];
    _rightBtn.tag =2;
    _rightBtn.frame =CGRectMake((DEVICE_WIDTH-200)/2,(NAVBAR_HIGHT-44)/2+10, 200, 44);
    [_rightBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = FONT(14);
    [_rightBtn addTarget:self action:@selector(clieckEvent:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:_rightBtn];
    UIView* linev = [[UIView alloc]initWithFrame:CGRectMake(0, NAVBAR_HIGHT-0.5, topView.frame.size.width, 0.5)];
    linev.backgroundColor =UIColorFromRGB(0xd8d8d8);
    [topView addSubview:linev];
    linev=nil;
    [self.view addSubview:topView];
    topView=nil;
}
-(void)clieckEvent:(id)sender
{
    UIButton*btn =(UIButton*)sender;
    switch (btn.tag) {
        case 1:
        {
            if ([_delegate respondsToSelector:@selector(cameraDidCancel)]) {
                [_delegate cameraDidCancel];
            }
        }
            break;
        case 2:
        {
            [self showMenu:sender];
        }
            break;
        default:
            break;
    }
}
- (void)setNavigationTitle:(NSString *)title
{
    [self.rightBtn setTitle:[NSString stringWithFormat:@"%@ ▾", title] forState:UIControlStateNormal];
    
}
- (void)showMenu:(UIView *)sender
{
    NSMutableArray *menuItems = [NSMutableArray array];
    
    for (ALAssetsGroup *group in self.groups) {
        
        [menuItems addObject:[KxMenuItem menuItem:[group valueForProperty:ALAssetsGroupPropertyName]
                                            image:nil
                                           target:self
                                           action:@selector(changeGroup:)]];
    }
    
    if (menuItems.count) {
        [KxMenu showMenuInView:self.view
                      fromRect:sender.frame
                     menuItems:menuItems];
    }
}
- (void)changeGroup:(KxMenuItem *)menu
{
    for (ALAssetsGroup *group in self.groups) {
        if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:[menu title]]) {
            self.assetsGroup = group;
            
            ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
                
                if (result) {
                    
                    [self.assets insertObject:result atIndex:0];
                    
                }
            };
            
            if (!self.assets) {
                _assets = [[NSMutableArray alloc] init];
            } else {
                [self.assets removeAllObjects];
            }
            
            [self.assetsGroup enumerateAssetsUsingBlock:assetsEnumerationBlock];
            
            [self addImageFirstRow];
            
            [self.collectionView reloadData];
            
            [self setNavigationTitle:[menu title]];
        }
    }
}
//
-(void)initData
{
    if (self.cameraImage == nil) {
        self.cameraImage = [UIImage imageNamed:@"paizhao.png"];
    }
    if (self.assetsLibrary == nil) {
        _assetsLibrary = [[ALAssetsLibrary alloc] init];
    }
    
    if (self.groups == nil) {
        _groups = [[NSMutableArray alloc] init];
    } else {
        [self.groups removeAllObjects];
    }
    
    if (!self.assets) {
        _assets = [[NSMutableArray alloc] init];
    } else {
        [self.assets removeAllObjects];
    }
    
    ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
        
        if (result) {
            [self.assets insertObject:result atIndex:0];
        }
        
        if ([self.assetsGroup numberOfAssets] - 1 == index) {
            
            [self.collectionView reloadData];
            
        }
    };
    
    ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
        
        ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
        [group setAssetsFilter:onlyPhotosFilter];
        if ([group numberOfAssets] > 0)
        {
            if ([[group valueForProperty:ALAssetsGroupPropertyType] intValue] == ALAssetsGroupSavedPhotos) {
                
                self.assetsGroup = group;
                
                if (self.assets.count == 0) {
                    
                    [self.assetsGroup enumerateAssetsUsingBlock:assetsEnumerationBlock];
                    
                    [self addImageFirstRow];
                    
                }
                [self setNavigationTitle:[group valueForProperty:ALAssetsGroupPropertyName]];
                [self.groups insertObject:group atIndex:0];
                
            }
            else {
                [self.groups addObject:group];
            }
        }
        
        
    };
    
    // enumerate only photos
    NSUInteger groupTypes = ALAssetsGroupAll;
    
    [self.assetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:listGroupBlock failureBlock:^(NSError *error) {
        
    }];
    
    ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
    [self.assetsGroup setAssetsFilter:onlyPhotosFilter];
}
- (void)addImageFirstRow
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        
        [self.assets insertObject:self.cameraImage atIndex:0];
        
    }
}

#pragma  UICollectionView
-(void)initCollectionView
{
    CGFloat colum = 3.0, spacing = 4.0;
    CGFloat value = floorf((CGRectGetWidth(self.view.bounds) - (colum - 1) * spacing) / colum);
    
    UICollectionViewFlowLayout *layout  = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize                     = CGSizeMake(value, value);
    layout.sectionInset                 = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumInteritemSpacing      = spacing;
    layout.minimumLineSpacing           = spacing;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NAVBAR_HIGHT, self.view.frame.size.width, self.view.frame.size.height-NAVBAR_HIGHT) collectionViewLayout:layout];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    layout =nil;
    
    [self.collectionView registerClass:[ZCameraPickerCell class] forCellWithReuseIdentifier:@"ZCameraPickerCell"];
    
    
}
//collectionView的代理方法
#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.assets.count;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"ZCameraPickerCell";
    ZCameraPickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    if (!cell) {
        NSLog(@"无法创建CollectionViewCell时打印，自定义的cell就不可能进来了。");
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // this makes sure the change notification happens on the MAIN THREAD
        ALAsset *asset;
        CGImageRef thumbnailImageRef;
        UIImage *thumbnail;
        
        if ([self.assets[indexPath.row] isKindOfClass:[UIImage class]]) {
            
            thumbnail = self.assets[indexPath.row];
            
        } else {
            
            asset = self.assets[indexPath.row];
            thumbnailImageRef = [asset aspectRatioThumbnail];
            if (thumbnailImageRef == nil) {
                thumbnailImageRef = [asset thumbnail];
            }
            thumbnail = [UIImage imageWithCGImage:thumbnailImageRef];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
             cell.imgView.image = thumbnail;
        });
        
    });
    
   
    return cell;
    
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"选择%ld",indexPath.row);
    if (indexPath.row == 0 && [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        
        ZCameraViewController *viewController = [[ZCameraViewController alloc] init];
        viewController.delegate = _delegate;
        [self.navigationController pushViewController:viewController animated:YES];
        
    }else{
        UIImage *image = [UIImage imageWithCGImage:[[[self.assets objectAtIndex:indexPath.row] defaultRepresentation] fullScreenImage]];
        ZCameraPhotoCrop *viewController = [ZCameraPhotoCrop newWithDelegate:_delegate photo:image];
        [self.navigationController pushViewController:viewController animated:YES];
  
    }
    
    
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
@end
